package org.algorithm.熊猫.链表;


import org.algorithm.common.ListNode;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/*****
 *
 *      周末的题：  周一要看，  没写的， 嘿嘿。。。   你们懂的
 *   参考uri: https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
 *
 */
public class K个一组反转链表 {

    @Test
    public void test() {
        ListNode node = ListNode.build(1, 2, 3);
        System.out.println();
        ListNode.print(reverseKGroup(node, 2));
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        int count = 0;
        //头节点
        ListNode dyNode = null;
        //当前节点
        ListNode curtNode = head;
        List<ListNode> arr = new ArrayList<>();
        while (curtNode != null) {
            count++;
            ListNode next = curtNode.next;
            curtNode.next = dyNode;
            dyNode = curtNode;
            curtNode = next;
            if (count == 1) {
                //尾巴节点
                arr.add(dyNode);
            }
            if (count == k) {
                //头节点
                arr.add(dyNode);
                dyNode = null;
                count = 0;
            }
        }

        // 不够一次区间
        if (arr.size() == 1) {
            ListNode headNode = null;
            while (dyNode != null) {
                ListNode next = dyNode.next;
                dyNode.next = headNode;
                headNode = dyNode;
                dyNode = next;
            }
            return head;
        }

        //刚好一次区间
        if (arr.size() == 2) {
            return arr.get(1);
        }

        //多次区间
        ListNode endNode = arr.get(0);
        ListNode result = arr.get(1);
        int i1 = arr.size() % 2;
        for (int i = 2; i < arr.size(); i += 2) {
            if (i + 1 == arr.size() && i1 != 0) {
                ListNode headNode = null;
                while (dyNode != null) {
                    ListNode next = dyNode.next;
                    dyNode.next = headNode;
                    headNode = dyNode;
                    dyNode = next;
                }
                endNode.next = headNode;
                return result;
            }
            endNode.next = arr.get(i + 1);
            endNode = arr.get(i);
        }

        return result;


    }
}
